using System;
using System.IO;
using System.Text;
using HtmlAgilityPack;

namespace weatherService
{
  public static class OpenByParser
  {
    const string c_id = "middleColumn";

    public static string Parse(Stream stream, Encoding encoding)
    {
      HtmlDocument doc = new HtmlDocument();
      doc.Load(stream, encoding);
      HtmlNode mainDivNode = doc.DocumentNode.SelectSingleNode("//div[@class='" + c_id + "']");
      if (mainDivNode == null)
        return string.Format("DIV with class=[{0}] not found", c_id);

      mainDivNode.InnerHtml = mainDivNode.InnerHtml.Replace(@"http://pogoda.open.by/", "/modules/Weather/");
      mainDivNode.InnerHtml = mainDivNode.InnerHtml.Replace(@"pogoda.open.by", "legion.aplus.by");
      mainDivNode.InnerHtml = mainDivNode.InnerHtml.Replace(@"/Content/Img", @"/modules/Weather/img");

      Clean(mainDivNode);
      RemoveScripts(mainDivNode);
      UpdateTHs(mainDivNode);
      string res = AddCss(mainDivNode);
      return res;
    }

    private static void Clean(HtmlNode mainDivNode)
    {
      HtmlNode bannerNode = mainDivNode.SelectSingleNode("//div[@class='middleBanner']");
      if (bannerNode != null) bannerNode.ParentNode.RemoveChild(bannerNode);
      HtmlNode detailsNode = mainDivNode.SelectSingleNode("//div[@class='links detailPage']");
      if (detailsNode != null) detailsNode.ParentNode.RemoveChild(detailsNode);
      HtmlNode rememberNode = mainDivNode.SelectSingleNode("//div[@class='remember']");
      if (rememberNode != null) rememberNode.ParentNode.RemoveChild(rememberNode);
    }

    private static string AddCss(HtmlNode mainDivNode)
    {
      var cssFiles = new[] { "style.css" };
      string res = mainDivNode.OuterHtml;
      foreach (var cssFile in cssFiles)
      {
        var htmlToFix = string.Format("<link rel=\"stylesheet\" type=\"text/css\" href=\"modules/Weather/{0}\"/>", cssFile);
        res = res.Insert(0, htmlToFix + Environment.NewLine);
      }
      return res;
    }

    private static void RemoveScripts(HtmlNode mainDivNode)
    {
      HtmlNodeCollection scriptNodes = mainDivNode.SelectNodes("//script");
      foreach (var node in scriptNodes)
        node.ParentNode.RemoveChild(node);
    }

    private static void UpdateTHs(HtmlNode mainDivNode)
    {
      HtmlNodeCollection scriptNodes = mainDivNode.SelectNodes("//th[@colspan='4']");
      foreach (var node in scriptNodes)
      {
        node.Attributes.Append("class", "thClass");
      }
    }

    public static string Parse(Stream stream)
    {
      return Parse(stream, Encoding.UTF8);
    }
  }
}